﻿using BaseUi.Models;
using HandyControl.Properties.Langs;
using Ping9719.DeviceCommunication;
using Ping9719.DeviceCommunication.Common.Helpers;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseUi.Device
{
    public class CeShiBan : Ping9719.DeviceCommunication.SerialPortBase
    {/// <summary>
     /// 使用串口的方式
     /// </summary>
        public CeShiBan(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            if (serialPort == null)
                serialPort = new SerialPort();
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;
            serialPort.DataBits = dataBits;
            serialPort.StopBits = stopBits;
            serialPort.Encoding = Encoding.UTF8;
            serialPort.Parity = parity;
        }
        /// <summary>
        /// 传感器，单位mv
        /// </summary>
        /// <returns></returns>
        public static byte[] SetSensor()
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x07, 0x01, 0x01, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }
        /// <summary>
        /// 通断检测
        /// </summary>
        /// <returns></returns>
        public static byte[] Onoff()
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x07, 0x01, 0x02, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }
        /// <summary>
        /// HZ检测电频
        /// </summary>
        /// <returns></returns>
        public static byte[] Frequency(int addr)
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x08, 0x01, 0x03, addr, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }/// <summary>
         /// UA检测电流
         /// </summary>
         /// <returns></returns>
        public static byte[] Current(int addr)
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x08, 0x01, 0x04, addr, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }
        /// <summary>
        /// HZ检测电频自检
        /// </summary>
        /// <returns></returns>
        public static byte[] Frequencycheck(int addr)
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x08, 0x02, 0x03, addr, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }/// <summary>
         /// UA检测电流自检
         /// </summary>
         /// <returns></returns>
        public static byte[] Currentcheck(int addr)
        {
            List<int> bytes = new List<int> { 0x55, 0xAA, 0x08, 0x02, 0x04, addr, 0xAA, 0x55 };
            var order = bytes.ConvertAll<byte>(it => Convert.ToByte(it)).ToArray();
            return order;
        }
        /// <summary>
        /// 传感器，单位mv
        /// </summary>
        /// <param name="timeout">保持时长（毫秒），填写解码设置：触发超时时间设置的值</param>
        /// <returns></returns>
        //public Result<string> ReadOne(int timeout)
        //{
        //    if (isAutoOpen)
        //    {
        //        var conn = Connect();
        //        if (!conn.IsSucceed)
        //            return new Result<string>(conn);
        //    }

        //    serialPort.ReadTimeout = timeout;
        //    serialPort.WriteTimeout = timeout;
        //    var result = new Result<string>();
        //    try
        //    {
        //        //清空字符,还原状态
        //        serialPort.DiscardInBuffer();
        //        var send = SetSensor();
        //        serialPort.Write(send, 0, send.Length);
        //        var aaa = SerialPortRead();
        //        if (!aaa.IsSucceed)
        //            return new Result<string>(aaa);

        //        result.Value = Encoding.UTF8.GetString(aaa.Value);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.IsSucceed = false;
        //        result.Err = ex.Message;
        //    }
        //    finally
        //    {
        //        if (isAutoOpen)
        //            Dispose();
        //    }
        //    return result.EndTime();
        //}
        /// <summary>
        /// 测试传感器，单位mv
        /// </summary>
        /// <param name="timeout">保持时长（毫秒），填写解码设置：触发超时时间设置的值</param>
        /// <returns></returns>
        public Result<string> ReadSensor(int timeout = 3000)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = SetSensor();
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);
                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 2 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                for (int i = 0; i < 1; i++)
                {
                    bytes[0] = aaa.Value[5 + (i * 2)];
                    bytes[1] = aaa.Value[5 + (i * 2) + 1];
                    var temp = (bytes[0] << 8) | (bytes[1]);
                    s = s + " " + temp;
                }
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.sensor)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
                //result.Value = Encoding.UTF8.GetString(aaa.Value);
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
        /// <summary>
        /// 通断检测
        /// </summary>
        /// <returns></returns>
        public Result<string> ReadOnoff(int timeout = 3000)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = Onoff();
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);
                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 16 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                for (int i = 0; i < 8; i++)
                {
                    bytes[0] = aaa.Value[5 + (i * 2)];
                    bytes[1] = aaa.Value[5 + (i * 2) + 1];
                    var temp = (bytes[0] << 8) | (bytes[1]);
                    s = s + " " + temp;
                }
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.breakmake)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
        /// <summary>
        /// HZ检测电频
        /// </summary>
        /// <returns></returns>
        public Result<string> ReadFrequency(int timeout = 3000, int arrd = 0)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = Frequency(arrd);
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);

                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 2 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                for (int i = 0; i < 1; i++)
                {
                    bytes[0] = aaa.Value[6 + (i * 2)];
                    bytes[1] = aaa.Value[6 + (i * 2) + 1];
                    var temp = (bytes[0] << 8) | (bytes[1]);
                    s = s + " " + temp;
                }
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.breakhz)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
        /// <summary>
        /// HZ检测电频自检
        /// </summary>
        /// <returns></returns>
        public Result<string> ReadFrequencycheck(int timeout = 3000, int arrd = 0)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = Frequencycheck(arrd);
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);

                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 2 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                for (int i = 0; i < 1; i++)
                {
                    bytes[0] = aaa.Value[6 + (i * 2)];
                    bytes[1] = aaa.Value[6 + (i * 2) + 1];
                    var temp = (bytes[0] << 8) | (bytes[1]);
                    s = s + " " + temp;
                }
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.zjbreakhz)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
        /// <summary>
        /// UA检测电流
        /// </summary>
        /// <returns></returns>
        public Result<string> ReadCurrent(int timeout = 3000, int arrd = 0)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = Current(arrd);
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);

                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 1 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                //for (int i = 0; i < 1; i++)
                //{
                //    bytes[0] = aaa.Value[6 + (i * 2)];
                //    bytes[1] = aaa.Value[6 + (i * 2) + 1];
                //    var temp = (bytes[0] << 8) | (bytes[1]);
                //    s = s + " " + temp;
                //}
                s = Convert.ToString(aaa.Value[6], 10);
                //var s11 = Convert.ToInt32(aaa.Value[6].ToString("X2"), 2);
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.breakua)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
        /// <summary>
        /// UA检测电流自检
        /// </summary>
        /// <returns></returns>
        public Result<string> ReadCurrentcheck(int timeout = 3000, int arrd = 0)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn);
            }

            serialPort.ReadTimeout = timeout;
            serialPort.WriteTimeout = timeout;
            var result = new Result<string>();
            try
            {
                //清空字符,还原状态
                serialPort.DiscardInBuffer();
                var send = Currentcheck(arrd);
                serialPort.Write(send, 0, send.Length);
                var aaa = SerialPortRead();
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa);

                if (aaa.Value == null || aaa.Value.Length == 0)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "无信息";
                    return new Result<string>(aaa);
                }
                if (send.Length + 1 != aaa.Value.Length)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = "长度错误";
                    return new Result<string>(aaa);
                }
                //if (!CRC16.CheckCRC16new(aaa.Value))
                //{
                //    aaa.IsSucceed = false;
                //    aaa.Value = new byte[] { };
                //    aaa.Err = "数据CRC16验证不合格";
                //    return new Result<string>(aaa); ;
                //}
                string set = "";
                byte[] bytes = new byte[2];
                string s = "";
                //for (int i = 0; i < 1; i++)
                //{
                //    bytes[0] = aaa.Value[6 + (i * 2)];
                //    bytes[1] = aaa.Value[6 + (i * 2) + 1];
                //    var temp = (bytes[0] << 8) | (bytes[1]);
                //    s = s + " " + temp;
                //}
                s = Convert.ToString(aaa.Value[6], 10);
                for (int i = 0; i < aaa.Value.Length; i++)
                {
                    set += aaa.Value[i].ToString("X2") + " ";
                    result.Value += aaa.Value[i].ToString("X2") + " ";
                    if (i == 4 && set != PortModel.zjbreakua)
                    {
                        aaa.IsSucceed = false;
                        aaa.Err = set + "前缀错误";
                        return new Result<string>(aaa);
                    }
                    //if (i >4&& i <= aaa.Value.Length - 3)
                    //{
                    //    result.Value += aaa.Value[i].ToString("X2");
                    //}
                    if (i == aaa.Value.Length - 3)
                    {
                        set = "";
                    }
                }                 //方法1
                if (set != PortModel.testend)
                {
                    aaa.IsSucceed = false;
                    aaa.Err = set + "结尾错误";
                    return new Result<string>(aaa);
                }
                result.Value = s.Trim();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }
    }
}
